import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

/**
 * ScratchGui
 */
public class ScratchGui {

    // 0 - ready to draw
    // 1 - need to flush background
    int draw_state = 1;
    int start_x,start_y;
    Color color;
    public static void main(String[] args) {
        ScratchGui gui =  new ScratchGui();
        gui.run();
    }
    public void run()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel()
        {
            protected void paintComponent(Graphics g) {
                // white background
                if(draw_state==1) 
                {
                    flush(g);
                    draw_state = 0;
                }
            }
            private void flush(Graphics g)
            {
                g.setColor(Color.WHITE);
                g.fillRect(0, 0, this.getWidth(), this.getHeight());
            }
        };

        panel.repaint();

        panel.addMouseListener(
            new MouseAdapter() {
                // public void mouseClicked(MouseEvent e) {
                //     System.out.println("Mouse Clicking!");
                // };
                public void mousePressed(MouseEvent e) {
                    // init drawing
                    if(e.getButton() == e.BUTTON1) color = Color.BLACK;
                    else if(e.getButton()==e.BUTTON3)color = Color.WHITE;

                    start_x = e.getX();
                    start_y = e.getY();
                };
            }
        );
        panel.addMouseMotionListener(
            new MouseAdapter()
            {
                public void mouseDragged(MouseEvent e) {
                    int new_x = e.getX();
                    int new_y = e.getY();
                    Graphics2D pg = (Graphics2D) (panel.getGraphics());
                    // left and right (use internal state color to represent)
                    pg.setColor(color);
                    // set stroke relate to speed
                    float stroke_width =(float)(10 * Math.pow(Math.E, -(Math.pow(start_x-new_x,2)+Math.pow(start_y-new_y,2))) );//(float) Math.pow(1/(Math.pow(start_x-new_x,2)+Math.pow(start_y-new_y,2)),);
                    pg.setStroke( new BasicStroke(stroke_width) );
                    pg.drawLine(start_x, start_y, new_x, new_y);

                    start_x = new_x;
                    start_y = new_y;
                };
            }
        );

        frame.getContentPane().add(BorderLayout.CENTER, panel);

        frame.setSize(500, 500);
        frame.setVisible(true);
    }
}